package de.dopichaj.labrador.util;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

/**
 * A class for assembling simple statistics (mean, sum, minimum, maximum) of
 * <code>int</code> values.
 * Note that {@link #add(int)} must be called at least once before the statistics
 * functions are called.
 */
public final class MeanCounter {

    private long sum = 0;
    private long count = 0;
    private long squareSum = 0;
    private int min = Integer.MAX_VALUE;
    private int max = Integer.MIN_VALUE;
    private final CountingMap<Integer> counts = new CountingMap<Integer>();
    /**
     * A list of all entries in <code>counts</code>, sorted by value.
     */
    private List<Entry<Integer, Integer>> values = null;
    
    /**
     * Add the given value to the statistics.
     */
    public void add(final int summand) {
        sum += summand;
        squareSum += summand * summand;
        count++;
        
        if (summand < min) {
            min = summand;
        }
        
        if (summand > max) {
            max = summand;
        }
        
        counts.count(summand);
        
        values = null;
    }

    /**
     * Return the arithmetic mean of all summands in all calls to {@link #add(int)}.
     */
    public double getMean() {
        return (double)sum / count;
    }
    
    /**
     * Return the median.
     */
    public int getMedian() {

        return getPercentile(.5);
    }
    
    /**
     * Return the first quantile.
     */
    public int getFirstQuantile() {

        return getPercentile(.25);
    }

    /**
     * Return the first quantile.
     */
    public int getThirdQuantile() {
        
        return getPercentile(.75);
    }

    private int getPercentile(final double percentile) {
        // sort the values
        sortValues();
        
        // find the first quantile and return it
        return findValueAt(values, (int)(percentile * count));
    }

    private void sortValues() {
        if (values == null) {
            values = new ArrayList<Map.Entry<Integer, Integer>>(counts.entrySet());
            Collections.sort(values, new Comparator<Map.Entry<Integer, Integer>>() {
                public int compare(Entry<Integer, Integer> o1, Entry<Integer, Integer> o2) {
                    return o1.getKey().compareTo(o2.getKey());
                }
            });
        }
    }

    /**
     * Find the smallest value at which at least <code>pos</code> values are
     * less than or equal to the returned value. 
     * @param values the values, sorted by value
     */
    private int findValueAt(final List<Entry<Integer, Integer>> values, final long pos) {
        
        final Iterator<Entry<Integer, Integer>> iterator = values.iterator();
        Entry<Integer, Integer> current = iterator.next();
        int currentPos = current.getValue();
        while (currentPos < pos) {
            current = iterator.next();
            currentPos += current.getValue();
        }
        return current.getKey();
    }
    
    public double getStandardDeviation() {
        return Math.sqrt((double)squareSum / count - (double)sum / count);
    }

    /**
     * Return the number of times {@link #add(int)} was called.
     */
    public long getCount() {
        return count;
    }

    /**
     * Return the sum of all summands in calls to {@link #add(int)}.
     */
    public long getSum() {
        return sum;
    }

    /**
     * Return the minumum summand in a call to {@link #add(int)}.
     */
    public int getMin() {
        return min;
    }
    
    /**
     * Return the mean summand in a call to {@link #add(int)}.
     */
    public int getMax() {
        return max;
    }

    @Override
    public String toString() {
        return "count " + getCount() + " mean " + getMean() +
            " stddev " + getStandardDeviation() +
            " median " + getMedian() +
            " max " + getMax() +
            " min " + getMin() +
            " q1 " + getFirstQuantile() +
            " q3 " + getThirdQuantile() +
            " p5 " + getPercentile(.05) +
            " p95 " + getPercentile(.95);
    }
}
/*
Copyright (c) 2007 Philipp Dopichaj

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/